<template>
	<view class="confirm-order-wrapper">
<!-- 		<view class="address-information-wrapper conteainer-public-style mg24">
			<view class="flex-c">
				<uni-tag text="默认"  style="background-color: #EC5581; border: none;" />
				<view class="province-city-area fz32">
					陕西省西安市雁塔区
				</view>
			</view>
			<view class="">
				<view class="flex-c-s">
					<text class="address-info fz32">电视塔地铁口192号（来安中心大厦）</text>
					<uni-icons type="forward" color="#999" size="22"></uni-icons>
				</view>
				
				<view class="consignee-phone fz26">
					<text>胡女士 18992837865</text>
				</view>
			</view>
		</view> -->
		
		<view class="order-goods-wrapper conteainer-public-style mg24">
			<view class="store-info flex-c">
				<image style="width: 36rpx; height: 36rpx; margin-right: 10rpx;" src="/static/images/store-b.png" mode=""></image>
				<text class="fz30">{{goodsInfo?.store?.storeName}}</text>
			</view>
			<view class="goods-order-info">
				<view class="goods-info  flex-c-s">
					<view class="">
						<image style="width: 200rpx; height: 200rpx; border-radius: 16rpx;" :src="goodsInfo.listImage" mode=""></image>
					</view>
					<view class="goods-name">
						<view class="fz30">
							{{ goodsInfo.name }}
						</view>
						<view class="mt10" v-if="goodsInfo?.productDetail && goodsInfo?.productDetail?.length">
							<uni-tag class="mr10 mb10" v-for="s of goodsInfo.productDetail[currentSpec].specCombo" :inverted="true" :key="s.specId"
							:text="`${s.specName}:${s.specValue}`" />
						</view>
						<view class="fz26 mt20" v-if="goodsInfo?.productDetail && goodsInfo?.productDetail?.length">
							<view class="">
								原价：￥<text class="color999 text-underline" v-if="goodsInfo?.productDetail?.length">{{ goodsInfo?.productDetail[currentSpec]?.originalPrice || 0 }}</text>
							</view>
							<view class="flex-c-s">
								<view class="">
									到手价：<text class="color-theme " v-if="goodsInfo?.productDetail?.length">￥{{ goodsInfo?.productDetail[currentSpec]?.sellingPrice || 0 }}</text>
								</view>
								<view class="">
									<uni-number-box :min="1" v-model="count"  @change="changeValue" />
								</view>
							</view> 
							
						</view>
					</view>
				</view>
				
			</view>
			<view class="add-remark flex-c-s" style="padding: 30rpx 0 0 0;">
				<text class="fz26">备注</text>
				<input v-model="remark" style="width: 500rpx; text-align: right; font-size: 28rpx;" type="text" placeholder="请输入(建议备注前先于商家沟通确认)" />
			</view>
		</view>
		
		<view class="pay-methods-wrapper conteainer-public-style mg24 fz30">
			<view class="pay-methods-title mb20">
				付款方式
			</view>
			<view class="pay-list fz26">
				<radio-group @change="radioChange">
					<!-- <label class="uni-list-cell uni-list-cell-pd flex-c-s b-b-1">
						<view class="flex-c">
							<image class="play-icon"  src="/static/images/wx-pay.png" mode=""></image>
							<view>微信支付</view>
						</view>
						<radio :value="payType.PayTypeWeChatPay" checked color="#F33C72" />
					</label> -->
					<label class="uni-list-cell uni-list-cell-pd flex-c-s b-b-1"> 
						<view class="flex-c">
							<image class="play-icon"  src="/static/images/zfb-pay.png" mode=""></image>
							<view>支付宝支付</view>
						</view>
						<radio :value="payType.PayTypeAliPay" :checked="type === payType.PayTypeAliPay" color="#F33C72" />
					</label>
					
					<label class="uni-list-cell uni-list-cell-pd flex-c-s b-b-1">
						<view class="flex-c">
							<image class="play-icon"  src="/static/images/image59@2x.png" mode=""></image>
							<view>金豆支付</view>
						</view>
						<radio :value="payType.PayTypeJinDou" :checked="type === payType.PayTypeJinDou" color="#F33C72" />
					</label>
					<label class="uni-list-cell uni-list-cell-pd flex-c-s">
						<view class="flex-c">
							<image class="play-icon"  src="/static/images/yueb.png" mode=""></image>
							<view>余额支付</view>
						</view>
						<radio :value="payType.PayTypeBalance" :checked="type === payType.PayTypeBalance" color="#F33C72" />
					</label>
				</radio-group>
			</view>
		</view>
		
		<view class="coupon-wrapper conteainer-public-style mg24">
			<view class="coupon-item flex-c-s">
				<text class="fz26">商品金额</text>
				<text class="fz22" v-if="goodsInfo?.productDetail && goodsInfo?.productDetail.length">¥ {{ goodsInfo?.productDetail[currentSpec]?.sellingPrice || 0 }}</text>
			</view>
			<view class="coupon-item flex-c-s">
				<text class="fz26">优惠券</text>
				<text class="fz22 color-theme">- ¥{{preferentialPrice}}</text>
			</view>
			<view class="flex-c-s">
				<text></text>
				<view ><text class="fz26">共{{count}}件，合计:</text> <text class="fz32">¥ {{totalPrice}}</text> </view>
			</view>
		</view>
		
		<view class="bottom-wrapper">
			<view class="submit-order flex-c-s">
				<view class="pay-total-mony">
					<text class="fz26">合计：</text>
					<text class="color-theme">￥ {{totalPrice}}</text>
				</view>
				<view class="">
					<button class="submit-btn" @click="paymentResult">提交订单</button>
				</view>
			</view>
		</view>
		<CustomeModal ref="customeModalNode" @confirmModal="confirmModal" @cancelModal="cancelModal" />
		<CustomeModal ref="tryCustomeModalNode" @confirmModal="tryConfirmModal" @cancelModal="cancelModal" content="正在尝试使用余额支付" />
		<!-- <Payment ref="paymentCom" /> -->
	</view>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, computed, ref } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { getStoreProductInfo, createOrder, paymentHadle } from '@/http/shop'
import { getOrderTime, awaitNextTick } from '@/utils/tools'
import { defaultPayType, payType } from '@/config' 
import type { IStoreGoods } from '@/types'

import CustomeModal from '@/components/CustomeModal.vue'

export default defineComponent({
	components: { CustomeModal },
	setup() {
		const paymentCom = ref()
		const customeModalNode = ref()
		const tryCustomeModalNode = ref()
		const state = reactive({
			currentSpec: 0,
			count: 1,
			remark: '',
			preferentialPrice: 0, // 优惠金额
			goodsInfo: {} as IStoreGoods,
			payType,
			type: defaultPayType,
			payMoney: 0,
			paymentPwd: '' as string | number, 
			tryCode: '',
			addressesId: 0
		})
		
		const changeValue = (e: number) => {
			//console.log(e);
		}
		
		const radioChange = (e: any) => {
			state.type = e.detail.value;
			
		}
		
		onLoad((option) => {
			if(option?.id) {
				state.currentSpec = option?.spec 
				state.addressesId = +option?.locationId || 0 
				getProductInfo(option?.id)
			} 
			console.log(option);
		})
		
		onShow(() => {
			uni.getStorage({
				key: 'userInfo',
				success(data) {
					let pwd = JSON.parse(data.data).paymentPwdFlag
					state.paymentPwd = pwd || 0  
				}
			})
		})
		
		const getProductInfo = async (id: number) => {
			let res = await getStoreProductInfo(id) 
			if(res.code === 0) {
				state.goodsInfo = res.data
			} 
		}
		
		const totalPrice = computed(() => {
			if(!state.goodsInfo?.productDetail || !state.goodsInfo?.productDetail?.length) return 0;
			let price = Number.parseFloat(String(state.goodsInfo.productDetail[state.currentSpec].sellingPrice * state.count - state.preferentialPrice)).toFixed(2)
			state.payMoney = +price;
			return price
		})
		
		const paymentResult = async () => {
			let pramas = {
				products: [{
					sku: state.goodsInfo.productDetail[state.currentSpec].sku,
					quantity: state.count
				}],
				remark: state.remark,
				payType: state.type,
				payPassword: '',
				addressesId: state.addressesId
			} 
			
			// return
			
			if(!state.goodsInfo?.productDetail.length) return;
			// if(!state.remark) {
			// 	uni.showToast({ title: '请输入备注信息', icon: 'none' })
			// 	return
			// }
			
			if(!state.paymentPwd || state.paymentPwd === 0) {
				uni.showModal({
					title: '支付提示',
					content: '您还未设置支付密码，是否前往设置？',
					success({confirm}) {
						if(confirm) {
							uni.navigateTo({
								url: '/pages/myPackge/setting/setPayPwd'
							})
						}
					}
				})
				return
			}
			if(state.type === 3 || state.type === 4) {
				customeModalNode.value.showModal()
			} else if(state.type === 2){
				let res = await createOrder(pramas)
				// console.log(pramas);
				console.log(res);
				if(res.code === 0) {
					uni.requestPayment({
					    provider: 'alipay',
					    orderInfo: res.data.payParam, 
					    async success(result) {
							uni.showToast({
								icon: 'success',
								title: '支付成功'
							})
					        // payStatusFun(1, res.data.payCode)
							await awaitNextTick(1500)
							toOrder()
					    },
					    fail: function (err) {
							state.type = 4
							console.log(err);
					        tryPayment(res.data.payCode, res.data.payType)
					    }
					});
				} else if(state.type == 2){
					uni.showToast({ title: res.msg||'订单创建失败', icon: 'none' })
				}
			}
			
			 
		}
		
		const payStatusFun = async(num: number, payCode: string)=>{
			//let resx = await ordersStatus(orderID);
			// console.log(getOrderTime(true));
			uni.redirectTo({
				url: `/pages/myPackge/payment/paymentStatus?payStatus=${num}&money=${state.payMoney}&time=${getOrderTime(true)}&orderNum=${payCode}`
			})
		}
		
		const confirmModal = async (content: string) => {
			let pramas = {
				products: [{
					sku: state.goodsInfo.productDetail[state.currentSpec].sku,
					quantity: state.count
				}],
				remark: state.remark,
				payType: state.type,
				payPassword: '',
				addressesId: state.addressesId
			} 
			if(state.type === 3 || state.type === 4) {
				if(content) {
					pramas.payPassword = content 
					let res = await createOrder(pramas) 
					// console.log(pramas);
					// console.log(res);
					if(res.code === 0) { 
						customeModalNode.value.cancel()
						uni.showToast({ title: '支付成功', icon: 'none' })
						await awaitNextTick(1500)
						toOrder()
						//payStatusFun(1, res.data.payCode)
					} else {
						customeModalNode.value.cancel()
						uni.showToast({ title: res.msg || '支付失败', icon: 'none' })  
						//payStatusFun(1, res.data.payCode) 
					}
				} else {
					uni.showToast({ title: '请输入支付密码', icon: 'none' })
					return
				}
				
			}  
		}
		
		const tryPayment = async (code:string, type: number) => { 
			state.tryCode = code
			tryCustomeModalNode.value.showModal()
		}
		
		const tryConfirmModal = async (content: string) => {
			if(content) {
				if( content) {
					// console.log(state.tryCode, 4, content);
					let res = await paymentHadle(state.tryCode, 4, content)  
					// console.log(res);
					if(res.code === 0) {
						tryCustomeModalNode.value.cancel()
						uni.showToast({ title: '支付成功', icon: 'none' }) 
						await awaitNextTick(1500)
						//payStatusFun(1, state.tryCode)
						toOrder()
					} else {
						tryCustomeModalNode.value.cancel()
						uni.showToast({ title: res.msg || '支付失败', icon: 'none' }) 
						await awaitNextTick()
						payStatusFun(0, state.tryCode) 
					}  
				} else {
					uni.showToast({ title: '已取消支付', icon: 'none' }) 
					return
				}
				 
			} else {
				uni.showToast({ title: '请输入支付密码', icon: 'none' })
				return
			}
		}
		
		const toOrder = () => {
			uni.redirectTo({
				url: `/pages/myPackge/order/index?status=${0}`
			})
		}
		
		const cancelModal = () => {
			uni.showToast({ title: '已取消支付', icon: 'error' })  
		}
		
		return {
			paymentCom,
			payStatusFun,
			totalPrice,
			changeValue,
			radioChange,
			paymentResult,
			customeModalNode,
			tryCustomeModalNode,
			confirmModal,
			tryConfirmModal,
			cancelModal, 
			...toRefs(state)
		}
	}
})
</script>

<style>
	page{background-color: #f8f8fa;}
</style>

<style lang="scss" scoped>
.confirm-order-wrapper{
	 padding-bottom: 200rpx;
	.address-information-wrapper{
		.province-city-area{
			margin-left: 10rpx;
		}
		.address-info{
			margin: 10rpx 0;
		}
	}
	.order-goods-wrapper{
		.goods-order-info{
			margin-top: 30rpx;
			
			.goods-info{
				width: 100%;
				align-items: flex-start;
			}
			.goods-name{ 
				flex: 1;
				margin-left: 18rpx;
			}
			.color-theme{
				padding: 20rpx 0;
			}
		}
	}
	.pay-methods-wrapper{
		.pay-list{
			.play-icon{
				width: 34rpx;
				height: 34rpx;
				margin-right: 16rpx;
			}
			.uni-list-cell{
				padding: 16rpx 0;
			}
		}
	}
	.coupon-wrapper{
		.coupon-item{
			margin-bottom: 36rpx;
		}
	}
	.submit-order{
		width: 100%;
		box-sizing: border-box;
		margin: 0 24rpx;
		.pay-total-mony{
			.color-theme{
				font-size: 42rpx;
			}
		}
		.submit-btn{
			color: #fff;
			line-height: 74rpx;
			width: 286rpx;
			height: 74rpx;
			background: linear-gradient(270deg,#eb57ae 0%, #eb5480);
			border-radius: 38rpx;
		}
	}
}

</style>